/*
******************
* author: 马丰彦
* date: 2019-05-08
* function: 封装axios
******************
*/

import axios from 'axios'
import { MessageBox } from 'element-ui'
import { showLoading, tryHideLoading } from './loading.js'
// import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'
// import Router from '@/router'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API1, // url = base url + request url
  // baseURL: window.configs.API_LOGIN, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      // 放置token进入headers
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // 请求错误
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 全局加载loading方法 (请求拦截器)
service.interceptors.request.use(
  config => {
    tryHideLoading() // 避免切换请求遮罩不消失，所以就先消失遮罩
    // ** 因为登录按钮触发两个请求，避免遮罩连续触发两次，再次取消一个 ** //
    if (config.url !== '/virtualCoupon/functionTypeList.do') {
      showLoading()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.resultCode !== '0000' && response.data.type !== 'application/vnd.ms-excel') {
      tryHideLoading()
      if (res.resultCode === '9995') {
        MessageBox.alert(res.resultDesc, '提示', {
          confirmButtonText: '确定',
          callback: action => {
            removeToken()
            window.location.replace(window.bossUrl.API_LOGIN)
            // store.dispatch('FedLogOut').then(() => {
            //   // location.reload() // 为了重新实例化vue-router对象 避免bug
            // })
          }
        })
      } else {
        console.log(res.resultDesc)
        MessageBox.alert(res.resultDesc, '提示', {
          confirmButtonText: '确定'
        })
        return false
      }
    } else {
      tryHideLoading()
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    tryHideLoading()
    MessageBox.alert('网络错误，请重试', '提示', {
      confirmButtonText: '确定',
      callback: action => {
        // ocation.reload()
        // window.history.go(-1)
        removeToken()
        window.location.replace(window.bossUrl.API_LOGIN)
        /* Router.replace({
          path: '/login'
        }) */
      }
    })
    return Promise.reject(error)
  }
)

export default service
